<template>
	<view class="container">
		<view class="tui-box">
			<tui-list-cell v-if="recinfo.recevierName" :arrow="true" unlined :radius="true" @click="chooseAddr">
				<view class="tui-address">
					<view v-if="true">
						<view class="tui-userinfo">
							<text class="tui-name">{{ recinfo.recevierName }}</text> {{ recinfo.receviePhone }}
						</view>
						<view class="tui-addr">
							<view class="tui-addr-tag">地址</view>
							<text>{{ recinfo.provinceName }}{{ recinfo.addressDetail }}</text>
						</view>
					</view>
					<view class="tui-none-addr" v-else>
						<image src="/static/images/index/map.png" class="tui-addr-img" mode="widthFix"></image>
						<text>选择收货地址</text>
					</view>
				</view>
				<view class="tui-bg-img"></view>
			</tui-list-cell>
			<view class="tui-top tui-goods-info">
				<tui-list-cell :hover="false" :lineLeft="false">
					<view class="tui-goods-title">
						商品信息
					</view>
				</tui-list-cell>
				<block v-for="(item,index) in orderGoodsList" :key="index">
					<tui-list-cell :hover="false" padding="0">
						<view class="tui-goods-item">
							<image :src="item.pic" class="tui-goods-img"></image>
							<view class="tui-goods-center">
								<view class="tui-goods-name">{{ item.productName }}</view>
								<view class="tui-goods-attr">{{ item.userSelectSpecText }}</view>
							</view>
							<view class="tui-price-right">
								<view>￥{{ item.price }}</view>
								<view>x{{ item.productNum }}</view>
							</view>
						</view>
					</tui-list-cell>
				</block>
				<tui-list-cell :hover="false">
					<view class="tui-padding tui-flex">
						<view>商品总额</view>
						<view>￥{{ totalNum }}</view>
					</view>
				</tui-list-cell>
				<!-- <tui-list-cell :arrow="hasCoupon" :hover="hasCoupon">
					<view class="tui-padding tui-flex">
						<view>优惠券</view>
						<view :class="{'tui-color-red':hasCoupon}">{{hasCoupon?"满5减1":'没有可用优惠券'}}</view>
					</view>
				</tui-list-cell> -->
				<tui-list-cell :hover="true" :arrow="true">
					<view class="tui-padding tui-flex">
						<view>发票</view>
						<view class="tui-invoice-text">暂不支持</view>
					</view>
				</tui-list-cell>
				<tui-list-cell :hover="true" :arrow="true" @click="chooseDeliveryMethod" v-if="false">
					<view class="tui-padding tui-flex">
						<view>配送方式</view>
						<view class="tui-placeholder-text">{{ selectedDeliveryMethod.txt }}</view>
					</view>
				</tui-list-cell>
				<tui-list-cell :hover="false">
					<view class="tui-padding tui-flex">
						<view>配送费</view>
						<view>￥0.00</view>
					</view>
				</tui-list-cell>
				<tui-list-cell :hover="true" :arrow="true" @click="triggerCoupon" v-if="couponEnable && couponList.length">
					<view class="tui-padding tui-flex">
						<view>优惠券</view>
						<view class="tui-placeholder-text">{{selectedCoupon ? `-&yen;${selectedCoupon.substractAmount}` : '选择优惠'}}</view>
					</view>
				</tui-list-cell>
				<tui-list-cell :hover="false" :lineLeft="false" padding="0">
					<view class="tui-remark-box tui-padding tui-flex">
						<view>订单备注</view>
						<input type="text" v-model="remark" class="tui-remark" placeholder="选填: 请先和商家协商一致" placeholder-class="tui-phcolor"></input>
					</view>
				</tui-list-cell>
				<tui-list-cell :hover="false" unlined>
					<view class="tui-padding tui-flex tui-total-flex">
						<view class="tui-flex-end tui-color-red">
							<view class="tui-black">合计： </view>
							<view class="tui-size-26">￥</view>
							<view class="tui-price-large">{{ totalNum }}</view>
						</view>
					</view>
				</tui-list-cell>
			</view>

			<!-- <view class="tui-top">
				<tui-list-cell unlined :hover="insufficient" :radius="true" :arrow="insufficient">
					<view class="tui-flex">
						<view class="tui-balance">余额支付<text class="tui-gray">(￥{{ totalNum }})</text></view>
						<switch color="#19be6b" class="tui-scale-small" v-show="!insufficient" />
						<view class="tui-pr-30 tui-light-dark" v-show="insufficient">余额不足, 去充值</view>
					</view>
				</tui-list-cell>
			</view> -->
		</view>
		<view class="tui-safe-area"></view>
		<view class="tui-tabbar">
			<view class="tui-flex-end tui-color-red tui-pr-20">
				<view class="tui-black">实付金额: </view>
				<view class="tui-size-26">￥</view>
				<view class="tui-price-large">{{ totalNum }}</view>
			</view>
			<view class="tui-pr25">
				<tui-button width="200rpx" height="70rpx" :size="28" type="danger" shape="circle" @click="validatePay">{{payBtnTxt}}</tui-button>
			</view>
		</view>
		<!-- <t-pay-way :show="show" @close="popupClose"></t-pay-way> -->
		
		<!-- 配送方式选择器 -->
		<t-delivery-way :show="showDeliveryMethod" @selected="confirmDeliveryMethods" @close="closeDeliveryMethod"></t-delivery-way>
		
		<t-coupon-picker
			:show="showCouponPicker"
			@close="triggerCoupon(false)"
			@picked="couponPicked"
			:coupons="couponList" picker />
	</view>
</template>

<script>
    import tPayWay from "@/components/views/t-pay-way/ti-pay-way"
	import tDeliveryWay from '@/components/views/t-delivery-way/t-delivery-way.vue'
	import tCouponPicker from '@/components/views/t-coupon-picker/t-coupon-picker.vue'
    import { mapState } from 'vuex'
	export default {
		components: {
			tPayWay,
			tDeliveryWay,
			tCouponPicker
		},
		data() {
			return {
				couponList: [],
				selectedCoupon: null,
				insufficient: false,
                show: false,
                orderGoodsList: [],
                totalNum: 0,    // 合计费用
                recinfo: {},    // 地址
                orderId: '',    // 订单号
                remark: '',     // 用户备注
				expressList: {},
				showDeliveryMethod: false, // 配送方式选择器是否显示
				showCouponPicker: false, //优惠券选择器是否显示
				// selectedDeliveryMethod: {
				// 	txt: '请选择',
				// 	code: -1
				// } // 被选中的配送方式
				selectedDeliveryMethod: {
					txt: '商家代发',
					code: 1
				}
			}
        },
        onLoad(option){

            const BUYLIST = this.BUYLIST

            if( BUYLIST && BUYLIST.length == 0 ){
                uni.showModal({
                    title: `错误提示`,
                    content: "非法进入",
                    showCancel: false
                })
                return
            }
			
			// console.log(BUYLIST, 'BUYLIST')

            this.countPrice()

            this.orderGoodsList = BUYLIST
			
			this.couponEnable && this.getCoupons()
            
			this.GetExpressList()
        },
        onShow(){
            const SELECT_ADDRESS = this.SELECT_ADDRESS
            // 更新选择的地址
            if( JSON.stringify(SELECT_ADDRESS) != "{}" ){
                this.recinfo = SELECT_ADDRESS
            }
			this.init()
        },
		methods: {
            async init(){
                await this.getAddressDefault()
            },
			countPrice() {
				// 计算下价格 处理下用户选择的规格的显示
				this.totalNum = 0
				this.BUYLIST.map(row => {
				    this.totalNum += (row.productNum * row.price)
				    try {
				        row.userSelectSpecText = (row.subProduct.productItemSpecDTOS || []).map(d => d.propertyName).join(', ')
				    } catch(err) {
				        console.log(err)
				    }
				})
			},
			// 获取物流信息列表
			async GetExpressList(){
				let { data } = await this.$api.GetExpressList()
				this.expressList = data
				// console.log(this.expressList,"this.expressList")
			},
            // 获取默认地址
            async getAddressDefault(){
                let response = await this.$api.getAddressList()
                const { data } = response
                // 这里因为你不知道哪个是默认地址，所以没办法，遍历一下吧
                let defaultAddress = Array.isArray(data) && data.filter(item => item.isDefault)[0]
				if( data.length == 0 ){
					uni.showModal({
						title:'温馨提示',
						content: '您还没有添加个人地址哦，速去添加吧',
						success(info) {
							if(info.confirm){								
								uni.navigateTo({
									url:'/pagesB/address/address'
								})
							}else{
								uni.navigateBack()
							}
						}
					})
					return
				}
                this.recinfo = defaultAddress
            },
            
			async validatePay() {
				let hasError = false
				if (this.selectedDeliveryMethod.code === -1) {
					hasError = true
					uni.showToast({
						title: '请选择配送方式'
					})
				}
				
				!hasError && this.toPayMent()
			},
			
			// 支付接口
            async toPayMent(){

                // 这里先确认订单
                let deliveryFee = 0
                let customerId = this.$store.state.customerId
                let merchantId = this.$store.state.merchantId
                let orderStatus = 1     // 订单状态
				let deliveryMode = this.selectedDeliveryMethod.code
				const { customerCouponId } = this.selectedCoupon || {}
				
				let deliveryDTO = {
					id: this.expressList[0].id
				}

                let { orderGoodsList, recinfo, totalNum:orderAmount, remark } = this.$data
                
                // 获取地址id
                let { id: addressId } = recinfo

                // 获取商品数量
                let productCounts = 0

                Array.isArray(orderGoodsList) && orderGoodsList.map(item=>{
                    productCounts += item.productNum
                })
				// OrderItemDTO
				const orderItemDTO = orderGoodsList.map(item => ({
					productItemId: item.subProduct.id,
					productItemNum: item.productNum
				}))

                let response = await this.$api.creatOrder({
                    addressId,
                    customerId,
                    merchantId,
                    items: orderItemDTO,
                    deliveryFee,
					deliveryMode,
                    orderAmount,
                    remark,
					deliveryDTO,
					customerCouponId
                })
				
				// 订单金额大于0, 配送方式不是货到付款时才需要调支付
				if (this.totalNum > 0 && deliveryMode !== 2) {
					this.$store.dispatch('USER_PAY',{
						orderId: response.data,
						success(data){
							uni.showToast({
								title:"支付成功"
							})
							uni.navigateTo({
								url: "/pagesB/success/success"
							})
						},
						fail(){
							uni.showToast({
								title:"支付失败"
							})
						}
					})
				} else {
					uni.navigateTo({
						url: "/pagesB/success/success?type=1"
					})
				}
            },
			chooseAddr() {
				uni.navigateTo({
					url: `/pagesB/address/address?type=select`
				})
			},
			btnPay() {
				this.show = true
			},
			popupClose() {
				this.show = false
			},
			chooseDeliveryMethod() {
				this.showDeliveryMethod = true
			},
			closeDeliveryMethod() {
				this.showDeliveryMethod = false
			},
			confirmDeliveryMethods(value) {
				this.selectedDeliveryMethod = value
				this.showDeliveryMethod = false
			},
			triggerCoupon(show = true) {
				this.showCouponPicker = show
			},
			async getCoupons() {
				const { merchantId: mid } = this.$config
				const { customerId } = this.$store.state
				const orderItems = this.orderGoodsList.map(({ productNum, subProduct }) => ({
					num: productNum,
					productItemId: subProduct.id
				}))

				const { success, data } = await this.$api.GetOrderCoupons(mid, customerId, orderItems)
				// console.log(data, 'data')
				if (success) {
					this.couponList = data.map(d => {
						d.isGet = true
						return d
					})
				}
			},
			couponPicked(coupon) {
				this.showCouponPicker = false
				this.selectedCoupon = coupon
				// 减少的金额
				const amount = Math.max(0, this.totalNum - coupon?.substractAmount || 0)
				if (coupon) {
					this.totalNum = parseFloat(amount).toFixed(2).toString()
				} else {
					this.countPrice()
				}
			}
        },
        computed:{
            ...mapState(["SELECT_ADDRESS", "BUYLIST"]),
			couponEnable() {
				return this.$config.couponEnable
			},
			payBtnTxt() {
				return this.totalNum > 0 ? '确认支付' : '确认下单'
			}
        }
	}
</script>

<style>
	.container {
		padding-bottom: 98rpx;
	}

	.tui-box {
		padding: 20rpx 0 118rpx;
		box-sizing: border-box;
	}

	.tui-address {
		min-height: 80rpx;
		padding: 10rpx 0;
		box-sizing: border-box;
		position: relative;
	}

	.tui-userinfo {
		font-size: 30rpx;
		font-weight: 500;
		line-height: 30rpx;
		padding-bottom: 12rpx;
	}

	.tui-name {
		padding-right: 40rpx;
	}

	.tui-addr {
		font-size: 24rpx;
		word-break: break-all;
		padding-right: 25rpx;
	}

	.tui-addr-tag {
		padding: 5rpx 8rpx;
		flex-shrink: 0;
		background: #EB0909;
		color: #fff;
		display: inline-flex;
		align-items: center;
		justify-content: center;
		font-size: 25rpx;
		line-height: 25rpx;
		transform: scale(0.8);
		transform-origin: 0 center;
		border-radius: 6rpx;
	}

	.tui-bg-img {
		position: absolute;
		width: 100%;
		height: 8rpx;
		left: 0;
		bottom: 0;
		background: url("") repeat;
	}

	.tui-top {
		margin-top: 20rpx;
		overflow: hidden;
	}

	.tui-goods-title {
		font-size: 28rpx;
		display: flex;
		align-items: center;
	}

	.tui-padding {
		box-sizing: border-box;
	}

	.tui-goods-item {
		width: 100%;
		padding: 20rpx 30rpx;
		box-sizing: border-box;
		display: flex;
		justify-content: space-between;
	}

	.tui-goods-img {
		width: 180rpx;
		height: 180rpx;
		display: block;
		flex-shrink: 0;
	}

	.tui-goods-center {
		flex: 1;
		padding: 20rpx 8rpx;
		box-sizing: border-box;
	}

	.tui-goods-name {
		max-width: 310rpx;
		word-break: break-all;
		overflow: hidden;
		text-overflow: ellipsis;
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 2;
		font-size: 26rpx;
		line-height: 32rpx;
	}

	.tui-goods-attr {
		font-size: 22rpx;
		color: #888888;
		line-height: 32rpx;
		padding-top: 20rpx;
		word-break: break-all;
		overflow: hidden;
		text-overflow: ellipsis;
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 2;
	}

	.tui-price-right {
		text-align: right;
		font-size: 24rpx;
		color: #888888;
		line-height: 30rpx;
		padding-top: 20rpx;
	}

	.tui-flex {
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: space-between;
		font-size: 26rpx;
	}

	.tui-total-flex {
		justify-content: flex-end;
	}

	.tui-color-red,
	.tui-invoice-text {
		color: #E41F19;
		padding-right: 30rpx;
	}
	.tui-placeholder-text {
		color: #888;
		padding-right: 30rpx;
	}

	.tui-balance {
		font-size: 28rpx;
		font-weight: 500;
	}

	.tui-black {
		color: #222;
		line-height: 30rpx;
	}

	.tui-gray {
		color: #888888;
		font-weight: 400;
	}

	.tui-light-dark {
		color: #666;
	}

	.tui-goods-price {
		display: flex;
		align-items: center;
		padding-top: 20rpx;
	}

	.tui-size-26 {
		font-size: 26rpx;
		line-height: 26rpx;
	}

	.tui-price-large {
		font-size: 34rpx;
		line-height: 32rpx;
		font-weight: 600;
	}

	.tui-flex-end {
		display: flex;
		align-items: flex-end;
		padding-right: 0;
	}

	.tui-phcolor {
		color: #B3B3B3;
		font-size: 26rpx;
	}

	/* #ifndef H5 */
	.tui-remark-box {
		padding: 22rpx 30rpx;
	}

	/* #endif */
	/* #ifdef H5 */
	.tui-remark-box {
		padding: 26rpx 30rpx;
	}

	/* #endif */

	.tui-remark {
		flex: 1;
		font-size: 26rpx;
		padding-left: 64rpx;
	}

	.tui-scale-small {
		transform: scale(0.8);
		transform-origin: 100% center;
	}

	.tui-scale-small .wx-switch-input {
		margin: 0 !important;
	}

	/* #ifdef H5 */
	>>>uni-switch .uni-switch-input {
		margin-right: 0 !important;
	}

	/* #endif */
	.tui-tabbar {
		width: 100%;
		height: calc(env(safe-area-inset-bottom) + 100rpx);
		background: #fff;
		position: fixed;
		left: 0;
		bottom: 0;
		display: flex;
		align-items: center;
		justify-content: flex-end;
		font-size: 26rpx;
		box-shadow: 0 0 1px rgba(0, 0, 0, .3);
		padding-bottom: env(safe-area-inset-bottom);
		z-index: 999;
	}

	.tui-pr-30 {
		padding-right: 30rpx;
	}

	.tui-pr-20 {
		padding-right: 20rpx;
	}

	.tui-none-addr {
		height: 80rpx;
		padding-left: 5rpx;
		display: flex;
		align-items: center;
	}

	.tui-addr-img {
		width: 36rpx;
		height: 46rpx;
		display: block;
		margin-right: 15rpx;
	}


	.tui-pr25 {
		padding-right: 25rpx;
	}

	.tui-safe-area {
		height: 1rpx;
		padding-bottom: env(safe-area-inset-bottom);
	}
</style>
